import {
  OrderStatus
} from './config';
import {
  fetchOrders,
  fetchOrdersCount,
} from '../../../services/order/orderList';
import {
  cosThumb
} from '../../../utils/util';
const $api = require('../../../utils/request').Api;
const app = getApp()
Page({
  page: {
    size: 10,
    num: 1,
    //这个目前没有找到是干什么的 这个代码真几把乱
    Mallstatus: 1,
  },

  data: {
    baseImgUrl: app.globalData.baseImgUrl,
    list: [
      {
      value: '全部',
      index: 10001,
    },
      {
        value: '待付款',
        index: 20001,
      },
      {
        value: '待发货',
        index: 30001,
      },
      {
        value: '待收货',
        index: 40001,
      },
      {
        value: '待评价',
        index: 50001,
      },
      {
        value: '退款/售后',
        index: 60001,
      }
    ],
    tabs: [
    //   {
    //   key: -1,
    //   text: '全部'
    // },
    //   {
    //     key: OrderStatus.PENDING_PAYMENT,
    //     text: '现场购',
    //     info: ''
    //   },
    //   {
    //     key: OrderStatus.PENDING_DELIVERY,
    //     text: '预售自提',
    //     info: ''
    //   },

      {
        key: OrderStatus.COMPLETE,
        text: '现场购',
        info: ''
      },
      {
        key: OrderStatus.GIFT_CARD,
        text: '礼品卡',
        info: ''
      },
      {
        key: OrderStatus.COMPLETE_BACK,
        text: '退货/售后',
        info: ''
      },
    ],
    curTab: -1,
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
    status: -1,
    listdata: [],
    neirongqu: 0
  },

  onLoad(query) {
    let status = parseInt(query.status);
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : OrderStatus.COMPLETE;
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onReachBottom() {
    if (this.data.neirongqu === 0) {

    } else {
      this.getOrderList(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    console.log(e);
    // const {
    // 	callback
    // } = e.detail;
    this.setData({
      pullDownRefreshing: true
    });
    this.refreshList(this.data.curTab)
         .then(() => {
      this.setData({
        pullDownRefreshing: false
      });
      // callback && callback();
    })
         .catch((err) => {
      this.setData({
        pullDownRefreshing: false
      });
      Promise.reject(err);
    });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    this.refreshList(status);
  },

  getOrderList(statusCode = -1, reset = false) {
    console.log('**************************', this.data.status);
    const params = {
      parameter: {
        pageSize: this.page.size,
        pageNum: this.page.num,
      },
    };
    if (statusCode !== -1) params.parameter.orderStatus = statusCode;
    this.setData({
      listLoading: 1
    });
    // let orderList = [];
    let status = this.data.status == -1 ? '' :
      this.data.status == 5 ? '0' :
        this.data.status == 10 ? '1' :
          this.data.status == 40 ? '2' :
            this.data.status == 60||this.data.status == 50 ? '5' : ''
    console.log(this.data.status);
    let source = this.data.status == 5||this.data.status == 50 ? 2 : 1
    // 状态 0:未付款 1:未发货 2:待收货 5:已完成  7:订单关闭
    let login = wx.getStorageSync('login')
    $api.orderList({
      userId: login.data.data.memberNumber,
      page: this.page.num++,
      size: this.page.size,
      status: status,
      source: source
    }).then(({ data: res }) => {
      console.log(res);
      const orderList = res.data.orderList.map(item => {
        item.goodsList.forEach(good => {
          good.productPrice = good.productPrice * good.num
        })
        return item
      })

      console.log('sm wan yi', orderList);
      if (orderList.length > 0) {
        const buttons = [{
          buttons: [{
            name: "取消订单",
            type: 2,
            primary: false
          },
            {
              name: "付款",
              type: 1,
              primary: true
            }
          ]
        }]
        const buttons4 = [{
          buttons: [{
            name: "申请售后",
            type: 4,
            primary: true
          },
            // {
            // 	name: "付款",
            // 	type: 1,
            // 	primary: true
            // }
          ]
        }]
        console.log(buttons);
        let listdatalia = this.data.listdata.concat(orderList)
        listdatalia.forEach((item, index) => {
          console.log(item);
          if (item.status === "未付款") {
            item.buttons = buttons[0].buttons
          }
        })
        this.setData({
          listLoading: 2,
          neirongqu: +(orderList.length === this.page.size),
          listdata: listdatalia
          // orderList: buttons[0]
        })
      } else {
        console.log('=====================================================');
        this.setData({
          neirongqu: 0,
          listLoading: 0,
            listdata: this.data.listdata.concat(orderList)
        })
      }

    })
    console.log(params);
    // return fetchOrders(params)
    // 	.then((res) => {
    // 		console.log(res);
    // 		this.page.num++;
    // 		let orderList = [];
    // 		if (res && res.data && res.data.orders) {
    // 			orderList = (res.data.orders || []).map((order) => {
    // 				return {
    // 					id: order.orderId,
    // 					orderNo: order.orderNo,
    // 					parentOrderNo: order.parentOrderNo,
    // 					storeId: order.storeId,
    // 					storeName: order.storeName,
    // 					status: order.orderStatus,
    // 					statusDesc: order.orderStatusName,
    // 					amount: order.paymentAmount,
    // 					totalAmount: order.totalAmount,
    // 					logisticsNo: order.logisticsVO.logisticsNo,
    // 					createTime: order.createTime,
    // 					goodsList: (order.orderItemVOs || []).map((goods) => ({
    // 						id: goods.id,
    // 						thumb: cosThumb(goods.goodsPictureUrl, 70),
    // 						title: goods.goodsName,
    // 						skuId: goods.skuId,
    // 						spuId: goods.spuId,
    // 						specs: (goods.specifications || []).map(
    // 							(spec) => spec.specValue,
    // 						),
    // 						price: goods.tagPrice ? goods.tagPrice : goods.actualPrice,
    // 						num: goods.buyQuantity,
    // 						titlePrefixTags: goods.tagText ? [{
    // 							text: goods.tagText
    // 						}] : [],
    // 					})),
    // 					buttons: order.buttonVOs || [],
    // 					groupInfoVo: order.groupInfoVo,
    // 					freightFee: order.freightFee,
    // 				};
    // 			});
    // 		}
    // 		return new Promise((resolve) => {
    // 			if (reset) {
    // 				this.setData({
    // 					orderList: []
    // 				}, () => resolve());
    // 			} else resolve();
    // 		}).then(() => {
    // 			this.setData({
    // 				orderList: this.data.orderList.concat(orderList),
    // 				listLoading: orderList.length > 0 ? 0 : 2,
    // 			});
    // 		});
    // 	})
    // 	.catch((err) => {
    // 		this.setData({
    // 			listLoading: 3
    // 		});
    // 		return Promise.reject(err);
    // 	});
  },

  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },
  onTabChange1(e) {
    if(!this.page){
      this.page={
        size: 500,
        num: 1,
        //这是干嘛的 如果你是下一个前端 恭喜你
        Mallstatus: 1,
      };
    }
    const { value } = e.detail;
    if (value === OrderStatus.COMPLETE_BACK) {
      // 售后列表，单独跳转
      return wx.navigateTo({ url: '/pages/order/after-service-list/index' })
    }
    this.setData({ status: value });
    if (value === 40) {
      this.setData({
        Mallstatus: 1
      })
    } else if (value === 5) {
      this.setData({
        Mallstatus: 1
      })
    } else {
      this.setData({
        Mallstatus: 0
      })
    }
    this.refreshList(value);
  },
  onTabChange2(e) {
    const {
      value
    } = e.detail;
    this.setData({
      Mallstatus: 1
    });
    this.refreshList(value);
  },

  getOrdersCount() {
    return fetchOrdersCount().then((res) => {
      const tabsCount = res.data || [];
      const {
        tabs
      } = this.data;
      tabs.forEach((tab) => {
        const tabCount = tabsCount.find((c) => c.tabType === tab.key);
        if (tabCount) {
          tab.info = tabCount.orderNum;
        }
      });
      this.setData({
        tabs
      });
    });
  },

  refreshList(status = -1) {
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({ curTab: status, orderList: [], listdata: [] });
    console.log(status);
    if (status === 10001 || status === 20001 || status === 30001 || status === 40001 || status === 50001 || status === 60001) {
      return Promise.all([
        this.getOrderList(status, true),
      ]);
    } else if (status === 5||status==50) {
      this.setData({
        Mallstatus: 1
      })
      return Promise.all([
        this.getOrderList(status, true),
        this.getOrdersCount(),
      ]);
    } else if (status === 40) {
      this.setData({
        Mallstatus: 1
      })
      return Promise.all([
        this.getOrderList(status, true),
        this.getOrdersCount(),
      ]);
    } else if (status === 51) {
      this.setData({
        Mallstatus: 1
      })
      return Promise.all([
        this.getRefundList(),
      ]);
    } else if (status === OrderStatus.GIFT_CARD) {
      return this.giftCardList()
    }
  },
  getRefundList(pageNum) {
    let login = wx.getStorageSync('login')

    $api.refundList({
      memberNumber: login.data.data.memberNumber,
      pagNum: this.page.num++,
      pagSize: this.page.size,
    }).then(({ data: res })=>{
      this.setData({
        neirongqu: 0,
        listLoading: 0,
        listdata: this.data.listdata.concat(res.data.refundList)
      })
    })
  },
  giftCardList() {
    const login = wx.getStorageSync('login')

    $api.giftCardList({
      memberNumber: login.data.data.memberNumber,
      pagNum: this.page.num++,
      pagSize: this.page.size,
    }).then(({ data: res })=>{
      this.setData({
        neirongqu: 0,
        listLoading: 0,
        listdata: this.data.listdata.concat(res.data.giftCardList)
      })
    })
  },
  onGoodsCardTap (e) {
    console.log(e)
    const { order } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/gift-detail/index?exchangeOrderCode=${order.exchangeOrderCode}`,
    });
  },
  onRefresh() {
    this.refreshList(this.data.curTab);
  },

  onOrderCardTap(e) {
    console.log(e);
    const {
      order
    } = e.currentTarget.dataset;
    let list = JSON.stringify(order)
    wx.navigateTo({
      url: `/pages/order/order-detail/index?orderNo=${list}`,
    });
  },
});
